// pages/review-list/review-list.js
const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    reviewList: [],
    showEditModal: false,
    editForm: {
      reviewId: null,
      productName: '',
      rating: 5,
      content: ''
    }
  },

  onLoad() {
    this.loadReviewList();
  },

  onShow() {
    this.loadReviewList();
  },

  loadReviewList() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      return;
    }

    app.showLoading();
    app.request({
      url: '/review/list',
      method: 'GET',
      data: {
        userId: userInfo.id,
        page: 1,
        size: 100
      }
    }).then(res => {
      if (res.success) {
        // 使用更高效的数据处理方式
        const reviews = (res.data.records || []).map(item => {
          const processedItem = { ...item };
          
          // 处理商品图片
          processedItem.productImage = item.productImage || this.getFirstImage(item.productImages);
          
          // 处理时间格式
          processedItem.createTime = util.formatDateTime(item.createTime);
          
          // 确保rating是数字类型
          processedItem.rating = parseInt(item.rating) || 0;
          
          // 调试信息
          console.log('处理评价数据:', {
            id: processedItem.id,
            rating: processedItem.rating,
            productName: processedItem.productName
          });
          
          return processedItem;
        });
        
        this.setData({ reviewList: reviews });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  getFirstImage(images) {
    if (!images || typeof images !== 'string') {
      return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    }
    
    // 使用更高效的方式获取第一张图片
    const firstImage = images.split(',')[0];
    return firstImage || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
  },

  previewImage(e) {
    const images = e.currentTarget.dataset.images;
    const current = e.currentTarget.dataset.current;
    wx.previewImage({
      current: current,
      urls: images
    });
  },

  // 打开修改评价弹窗
  editReview(e) {
    const review = e.currentTarget.dataset.review;
    this.setData({
      showEditModal: true,
      editForm: {
        reviewId: review.id,
        productName: review.productName,
        rating: review.rating,
        content: review.content
      }
    });
  },

  // 关闭修改评价弹窗
  closeEditModal() {
    this.setData({
      showEditModal: false,
      editForm: {
        reviewId: null,
        productName: '',
        rating: 5,
        content: ''
      }
    });
  },

  // 选择评分
  selectRating(e) {
    const rating = e.currentTarget.dataset.rating;
    this.setData({
      'editForm.rating': rating
    });
  },

  // 评价内容输入
  onContentInput(e) {
    this.setData({
      'editForm.content': e.detail.value
    });
  },

  // 提交修改
  submitEdit() {
    if (!this.data.editForm.content.trim()) {
      app.showToast('请输入评价内容');
      return;
    }

    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      app.showToast('请先登录');
      return;
    }

    app.showLoading('提交中...');
    app.request({
      url: '/review/update',
      method: 'POST',
      data: {
        reviewId: this.data.editForm.reviewId,
        userId: userInfo.id,
        content: this.data.editForm.content,
        rating: this.data.editForm.rating
      }
    }).then(res => {
      if (res.success) {
        app.showToast('修改成功', 'success');
        this.closeEditModal();
        this.loadReviewList();
      } else {
        app.showToast(res.message || '修改失败');
      }
    }).catch(err => {
      app.showToast('修改失败，请重试');
      console.error('修改评价失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  // 删除评价
  deleteReview(e) {
    const reviewId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除该评价吗？删除后将无法恢复。',
      success: (res) => {
        if (res.confirm) {
          const userInfo = wx.getStorageSync('userInfo');
          if (!userInfo) {
            app.showToast('请先登录');
            return;
          }

          app.showLoading('删除中...');
          app.request({
            url: '/review/delete',
            method: 'POST',
            data: {
              reviewId: reviewId,
              userId: userInfo.id
            }
          }).then(res => {
            if (res.success) {
              app.showToast('删除成功', 'success');
              this.loadReviewList();
            } else {
              app.showToast(res.message || '删除失败');
            }
          }).catch(err => {
            app.showToast('删除失败，请重试');
            console.error('删除评价失败', err);
          }).finally(() => {
            app.hideLoading();
          });
        }
      }
    });
  }
});


